class Post < ApplicationRecord
  has_many :post_type_rels ,dependent: :destroy
  belongs_to :user
  has_many :post_relationships, class_name: "Relationship",foreign_key: "post_id",dependent: :destroy
  validates :context, presence: true
  validates :title, presence: true
  validates :user_id, presence: true
  validate :picture_size

  #定义字段为图片
  mount_uploader :picture, PictureUploader

  # 删除评论
  def uncomment(user)
    active_relationships.find_by(comment_id: user.id).destroy
  end

  #创建评论
  def comment(post)
    post_relationships.create(post_id: post.id, comment_id: user.id)
  end

  private
  # 验证上传的图片大小
  def picture_size
    if picture.size > 5.megabytes
      errors.add(:picture, "should be less than 5MB")
    end
  end

end
